/**
 * Created by wry on 2015/5/14.
 */

var voucherService = require('../../services/backoffice/backOffice-voucherService');
var messageUtil = require('../../common/utils/messageUtil');
var toolUtil = require('../../common/utils/toolUtil');
var nodeExcel = require('excel-export');

exports.addVoucherType = function (req, res) {

    voucherService.addVoucherTypeService(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when addVoucherType ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

exports.getVoucherType = function (req, res) {
    voucherService.getVoucherTypeService(function (err, result) {
        if (err) {
            logger.error('Exception happened when getVoucherTypeService ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

exports.addRetailer = function (req, res) {
    var input = req.body;

    toolUtil.uploadImageService(null, null, req, function (err, images) {
        if (err) {
            res.json(messageUtil.composeFailedMessage(req, 'Failed to upload Images... - ' + err.message));
        } else {
            var data = new Array();

            images.forEach(function (image) {
                if (image != null) {
                    data.push(image);
                }
            });

            if (data.length > 0)
                input.retailer_icon = data[0];

            voucherService.addRetailerService(input, function (err, result) {
                if (err) {
                    logger.error('Exception happened when addRetailer ...!' + err.message);
                    res.json(messageUtil.composeFailedMessage(req, err.message));
                } else {
                    res.json(messageUtil.composeSucceededMessage(req, null, result));
                }
            })
        }
    });
};

exports.addMainRetailer = function (req, res) {
    var input = req.body;

    voucherService.addMainRetailerService(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when addMainRetailer ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};


exports.deleteMainRetailer = function (req, res) {
    var input = req.body;
    var id = req.body.id;

    voucherService.deleteMainRetailerService(id, function (err, result) {
        if (err) {
            logger.error('Exception happened when addMainRetailer ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            if (result != null) {
                logger.debug("delete success!");
                res.json(messageUtil.composeSucceededMessage(req, null, result));
            }else {
                logger.debug("delete failure, mainRetailer is not existing.");
                res.json(messageUtil.composeFailedMessage(req, "delete failure, mainRetailer is not existing.", id));
            }


        }
    })
};


exports.getRetailerList = function (req, res) {
    var parentId = req.params.parentId;

    voucherService.getRetailerListService(parentId, function (err, result) {
        if (err) {
            logger.error('Exception happened when getRetailerList ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

exports.searchRetailerByName = function (req, res) {

    //var parentId = req.body.parentId;
    //var name = req.body.name;
    var option = req.body;

    voucherService.searchRetailerByNameService(option, function (err, result) {
        if (err) {
            logger.error('Exception happened when searchRetailerByName ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

exports.bindRetailerCommunity = function (req, res) {
    var retailerId = req.body.retailerId;
    var communities = req.body.communities;

    voucherService.bindRetailerCommunityService(retailerId, communities, function (err, result) {
        if (err) {
            logger.error('Exception happened when bindRetailerCommunity ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    });

};
exports.getAllRetailers = function (req, res) {

    voucherService.getAllRetailers(function (err, result) {
        if (err) {
            logger.error('Exception happened when getAllRetailers ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    });
};

exports.getRetailerAgreement = function (req, res) {
    var retailerId = req.params.retailerId;

    voucherService.getRetailerAgreementService(retailerId, function (err, result) {
        if (err) {
            logger.error('Exception happened when getRetailerAgreement ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

exports.addRetailerAgreement = function (req, res) {
    var input = req.body;
    voucherService.addRetailerAgreementService(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when addRetailerAgreement ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

exports.deleteAgreement = function (req, res) {
    var id = req.params.id;
    voucherService.deleteAgreementService(id, function (err, result) {
        if (err) {
            logger.error('Exception happened when deleteAgreement ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

exports.getAgreementVoucher = function (req, res) {
    voucherService.getAgreementVoucherService(function (err, result) {
        if (err) {
            logger.error('Exception happened when getAgreementVoucher ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

exports.getBranchRetailer = function (req, res) {
    var communityId = req.params.communityId;
    var page = req.params.page;

    voucherService.getBranchRetailerService(communityId, page, function (err, result) {
        if (err) {
            logger.error('Exception happened when getBranchRetailer ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            var data = {
                totalPage: Math.ceil(result[0][0].count / listPageSize),
                list: result[1]
            }
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
};

exports.singleBindRetailer = function (req, res) {
    var input = req.body;
    voucherService.singleBindRetailerService(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when singleBindRetailer ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
}

exports.getRetailerExchangeList = function (req, res) {
    var input = req.body;
    voucherService.getRetailerExchangeList(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when getRetailerExchangeList ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            var result = {data: result[0], totalPage: result[1]};
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    });
};

exports.exportRetailerExchangeList = function (req, res) {
    var input = req.cparams;
    voucherService.getExportRetailerExchangeList(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when getRetailerExchangeList ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            var data = result[0];
            var conf = {};

            conf.cols = [{
                caption: '66编号',
                type: 'String'
            }, {
                caption: '商家店名',
                type: 'String'
            }, {
                caption: '小区名称',
                type: 'String'
            }, {
                caption: '获得人昵称',
                type: 'String'
            }, {
                caption: '代金券编号',
                type: 'String'
            }, {
                caption: '代金券金额',
                type: 'String'
            }, {
                caption: '生成日期',
                type: 'String'
            }, {
                caption: '交易日期',
                type: 'String'
            }, {
                caption: '结算日期',
                type: 'String'
            }, {
                caption: '结算状态',
                type: 'String'
            }, {
                caption: '币面结算金额',
                type: 'String'
            }, {
                caption: '商家奖励金额',
                type: 'String'
            }, {
                caption: '结算金额',
                type: 'String'
            }];

            var tempRows = new Array();
            for (var i = 0; i < data.length; i++) {
                var temp = new Array();
                temp.push(data[i].code);
                temp.push(data[i].retailer_name);
                temp.push(data[i].community_name);
                if (data[i].info == null || data[i].info == '') {
                    temp.push("");
                } else {
                    temp.push(data[i].info.nickName);
                }
                temp.push(data[i].card_no);
                temp.push(data[i].voucher_val + "");
                if (data[i].genTime != null) {
                    var genTime = new Date(data[i].genTime);
                    temp.push(genTime.getFullYear() + "-" + (genTime.getMonth() + 1) + "-" + genTime.getDate() + " " + genTime.getHours() + ":" + genTime.getMinutes());
                } else {
                    temp.push("");
                }
                if (data[i].create_time != null) {
                    var createTime = new Date(data[i].create_time);
                    temp.push(createTime.getFullYear() + "-" + (createTime.getMonth() + 1) + "-" + createTime.getDate() + " " + createTime.getHours() + ":" + createTime.getMinutes());
                } else {
                    temp.push("");
                }
                if (data[i].close_time != null) {
                    var closeTime = new Date(data[i].close_time);
                    temp.push(closeTime.getFullYear() + "-" + (closeTime.getMonth() + 1) + "-" + closeTime.getDate() + " " + closeTime.getHours() + ":" + closeTime.getMinutes());
                } else {
                    temp.push("");
                }
                if (data[i].status == 0) {
                    temp.push("未结算");
                } else {
                    temp.push("已结算");
                }
                temp.push(data[i].deal_price + "");
                temp.push(data[i].retailer_price + "");
                temp.push((parseInt(data[i].deal_price) + parseInt(data[i].retailer_price)) + "");

                tempRows.push(temp);
            }
            conf.rows = tempRows;

            var ret = nodeExcel.execute(conf);
            res.setHeader('Content-Type', 'application/vnd.openxmlformats');
            res.setHeader("Content-Disposition", "attachment; filename=" + "Report.xlsx");
            res.end(ret, 'binary');
        }
    });
};


exports.searchVoucher = function (req, res) {
    var input = req.body;
    var page = req.params.page;
    voucherService.searchVoucherService(input, page, function (err, result) {
        if (err) {
            logger.error('Exception happened when searchVoucher ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            var data = {
                list: result[0],
                totalPage: result[1]
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
};

exports.exportVoucherList = function (req, res) {
    var input = req.cparams;
    logger.info(input);
    voucherService.exportVoucherService(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when searchVoucher ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            var data = result[0];
            var conf = {};

            conf.cols = [{
                caption: '小区名称',
                type: 'String'
            }, {
                caption: '用户id',
                type: 'String'
            }, {
                caption: '获得人昵称',
                type: 'String'
            }, {
                caption: '获得原因',
                type: 'String'
            }, {
                caption: '代金券编号',
                type: 'String'
            }, {
                caption: '生成日期',
                type: 'String'
            }, {
                caption: '失效日期',
                type: 'String'
            }, {
                caption: '交易日期',
                type: 'String'
            }, {
                caption: '消费状态',
                type: 'String'
            }, {
                caption: '礼品券金额',
                type: 'String'
            }, {
                caption: '币面结算金额',
                type: 'String'
            }, {
                caption: '商家奖励金额',
                type: 'String'
            }];

            var tempRows = new Array();
            for (var i = 0; i < data.length; i++) {
                var temp = new Array();
                temp.push(data[i].community_name);
                temp.push(data[i].user_id);
                temp.push(data[i].nickName);
                if (data[i].reward_source == 1) {
                    temp.push("v认证");
                } else {
                    temp.push("推荐用户");
                }
                temp.push(data[i].card_no);
                var createTime = new Date(data[i].create_time);
                temp.push(createTime.getFullYear() + "-" + (createTime.getMonth() + 1) + "-" + createTime.getDate());
                if (data[i].expire_time != null) {
                    var expireTime = new Date(data[i].expire_time);
                    temp.push(expireTime.getFullYear() + "-" + (expireTime.getMonth() + 1) + "-" + expireTime.getDate());
                } else {
                    temp.push("");
                }
                if (data[i].spending_time != null) {
                    var spendingTime = new Date(data[i].spending_time);
                    temp.push(spendingTime.getFullYear() + "-" + (spendingTime.getMonth() + 1) + "-" + spendingTime.getDate());
                } else {
                    temp.push("");
                }
                if (data[i].is_use == 0) {
                    temp.push("未使用");
                } else {
                    temp.push("已使用");
                }
                if (data[i].voucher_val == null) {
                    temp.push("");
                } else {
                    temp.push(data[i].voucher_val + "");
                }
                if (data[i].deal_price == null) {
                    temp.push("");
                } else {
                    temp.push(data[i].deal_price + "");
                }
                if (data[i].retailer_price == null) {
                    temp.push("");
                } else {
                    temp.push(data[i].retailer_price + "");
                }

                tempRows.push(temp);
            }
            conf.rows = tempRows;

            var ret = nodeExcel.execute(conf);
            res.setHeader('Content-Type', 'application/vnd.openxmlformats');
            res.setHeader("Content-Disposition", "attachment; filename=" + "Report.xlsx");
            res.end(ret, 'binary');

            //res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
};


exports.getRetailerSettlement = function (req, res) {
    var input = req.body;

    voucherService.getRetailerSettlementService(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when getRetailerSettlement ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {

            var data = {
                list: result,
                opt: input
            };

            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
};

exports.retailerBalance = function (req, res) {
    var input = req.body;

    voucherService.retailerBalanceService(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when getRetailerSettlement ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {

            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

exports.getVoucherStatistics = function (req, res) {

    var input = req.body;
    voucherService.getVoucherStatistics(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when getVoucherStatistics ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            var result = {list: result[0], totalPage: result[1]};
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    });
};

exports.getConsumeStatistics = function (req, res) {

    var input = req.body;
    voucherService.getConsumeStatistics(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when getConsumeStatistics ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            var result = {list: result[0], totalPage: result[1]};
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    });
};

exports.getIsSettlementProfile = function (req, res) {

    var input = req.body;
    voucherService.getIsSettlementProfile(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when getIsSettlementProfile ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            var result = {list: result[0], totalPage: result[1]};
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    });
};

exports.tempExport = function (req, res) {
    voucherService.tempExport( function (err, result) {
        if (err) {
            logger.error('Exception happened when tempExport ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {

            var data = result;
            var conf = {};

            conf.cols = [{
                caption: '用户昵称',
                type: 'String'
            }, {
                caption: '用户id',
                type: 'String'
            }, {
                caption: '抽奖次数',
                type: 'String'
            }, {
                caption: '获得情值',
                type: 'String'
            }];

            var tempRows = new Array();
            for (var i = 0; i < data.length; i++) {
                var temp = new Array();
                temp.push(data[i].nickName);
                temp.push(data[i].user_id);
                temp.push(data[i].num+"");
                temp.push(data[i].rewardCount+"");

                tempRows.push(temp);
            }
            conf.rows = tempRows;

            var ret = nodeExcel.execute(conf);
            res.setHeader('Content-Type', 'application/vnd.openxmlformats');
            res.setHeader("Content-Disposition", "attachment; filename=" + "Report.xlsx");
            res.end(ret, 'binary');

            //res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
};